﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ggprot;

namespace GGTest
{
    public partial class Login : Form
    {
        private GaduProtocol protocol;
        private event EventHandler loggedIn;

        public Login()
        {
            InitializeComponent();
        }

        public GaduProtocol Protocol
        {
            get { return protocol; }
        }

        public int uin
        {
            get { return int.Parse(textBox1.Text); }
        }

        public string passwd
        {
            get { return maskedTextBox1.Text; }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (protocol != null)
                protocol.Dispose();
            DialogResult = System.Windows.Forms.DialogResult.Cancel;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            int aaa;
            if (int.TryParse(textBox1.Text, out aaa) && !string.IsNullOrEmpty(passwd))
            {
                button1.Enabled = false;
                protocol = new GaduProtocol();
                protocol.AddressObtained += new AddressObtainedEventHandler(protocol_AddressObtained);
                protocol.ObtainServer(uin);
            }
            else
                MessageBox.Show("Podaj poprawny numer oraz hasło");
        }

        void protocol_AddressObtained(object sender, AddressObtainedEventArgs e)
        {
            protocol.Connected += new EventHandler(protocol_Connected);
            protocol.Connect(protocol.ServerAddress, protocol.Port);
        }

        void protocol_Connected(object sender, EventArgs e)
        {
            protocol.LoginResponseReceived += new LoginResponseReceivedEventHandler(protocol_LoginResponseReceived);
            protocol.Login(uin, passwd);
            protocol.Users.Add(new User(5260413));
        }

        void protocol_LoginResponseReceived(object sender, LoginResponseReceivedEventArgs e)
        {
            button1.Invoke(new Action(delegate()
            {
                button1.Enabled = true;
                if (e.Status)
                    DialogResult = System.Windows.Forms.DialogResult.OK;
                else
                    MessageBox.Show("Podałeś złe hasło lub numer");
            }));
        }
    }
}
